package ft.app.gtig.service;

import com.haulmont.cuba.core.entity.FileDescriptor;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

@Service
public class QiNiuFileStorageService {

  private Logger log = LoggerFactory.getLogger(getClass());

  private String accessKey = "jg59ci6luJ4myP_hfTtkDxU8CL-bz-FasQ9NUWSu";
  private String secretKey = "0NZp_rgaaau4HQkeLa6_n_buQ7jpU2hZz_H8zuyQ";
  private String bucketName = "gtig";

  private String prefixURL = "http://oe52yf3ad.bkt.clouddn.com/";

  private Auth auth;
  private BucketManager bucketManager;

  private String uploadToken;
  private UploadManager uploadManager;


  @PostConstruct
  public void init() {
    auth = Auth.create(accessKey, secretKey);
    bucketManager = new BucketManager(auth);

    uploadManager = new UploadManager();

  }

  public void uploadFile(File file, String fileName) {
    try {
      uploadToken = auth.uploadToken(bucketName);
      uploadManager.put(file, fileName, uploadToken);
    } catch (QiniuException e) {
      Response r = e.response;
      log.error("res {}", r.toString());
    }
  }

  public InputStream downloadFile(FileDescriptor fileDescr) throws IOException {
    return URI.create(prefixURL + fileDescr.getId().toString()).toURL().openStream();
  }

  public void removeFile(FileDescriptor fileDescr) throws IOException {
    bucketManager.delete(bucketName, fileDescr.getId().toString());
  }

  public URL buildFileLink(FileDescriptor fileDescr) throws IOException {
    return URI.create(prefixURL + fileDescr.getId().toString()).toURL();
  }

  public boolean fileExists(FileDescriptor fileDescr) throws IOException {
    return bucketManager.stat(bucketName, fileDescr.getId().toString()) != null;
  }
}
